package heima.lm.oschina.vpfragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import heima.lm.oschina.BaseApplication;
import heima.lm.oschina.R;
import heima.lm.oschina.adapter.NewRvAdapter;
import heima.lm.oschina.base.BaseFragment;
import heima.lm.oschina.bean.News;
import heima.lm.oschina.bean.NewsList;
import heima.lm.oschina.constant.Constants;
import heima.lm.oschina.interf.OnRecyclerViewItemClickListener;
import heima.lm.oschina.utils.HttpUtils;
import heima.lm.oschina.utils.SpUtil;
import heima.lm.oschina.utils.UIUtils;

/**
 * Created by herenxue on 2017/4/1.
 * 热门
 */

public class HotSpotFragment extends BaseFragment {

    @BindView(R.id.srl_general_successful)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.rv_general_successful)
    RecyclerView mRecyclerView;


    private List<News> mNews;
    private NewRvAdapter mAdapter;

    private List<News> mRefreshNewses = new ArrayList<>();
    private List<News> mLoadNewses = new ArrayList<>();
    private int mRefreshPage = 0;
    private int mLoadPage = 0;
    private int lastVisibleItem;

    private Map<String, String> mParams;
    private HttpUtils<NewsList> mHttpUtils;
    private LinearLayoutManager mLayoutManager;

    @Override
    protected void loadSuccessPager() {
        View successfulView = View.inflate(UIUtils.getContext(), R.layout.fragment_general_successful, null);
        //注册ButterKnife
        ButterKnife.bind(this, successfulView);

        mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        mSwipeRefreshLayout.setProgressViewOffset(
                false,
                0,
                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));

        mLayoutManager = new LinearLayoutManager(UIUtils.getContext());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new NewRvAdapter(mNews);
        mRecyclerView.setAdapter(mAdapter);
        initEvent();
        mCommonPager.changeView(successfulView);
    }

    private void initEvent() {
        mAdapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
//                Toast.makeText(UIUtils.getContext(), "点击" + position, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent("heima.lm.os.china.detail.activity");
                Log.d("lm", mNews.get(position).getId() + "");
                News news = (News) mAdapter.getDatas().get(position);
                String id = String.valueOf(news.getId());
                String ids = SpUtil.getString(Constants.NEWS_IDS, "");
                if (!ids.contains(id)) {
                    ids += ids + "," + id;
                    SpUtil.saveString(Constants.NEWS_IDS, ids);
                }
                TextView tvNewsTitle = (TextView) v.findViewById(R.id.tv_news_title);
                tvNewsTitle.setTextColor(UIUtils.getColor(R.color.gray));
                TextView tvNewsContent = (TextView) v.findViewById(R.id.tv_news_content);
                tvNewsContent.setTextColor(UIUtils.getColor(R.color.gray));
                intent.putExtra("news_detail_id", String.valueOf(news.getId()));
                startActivity(intent);
            }
        });
        //下拉加载
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Toast.makeText(UIUtils.getContext(), "下拉刷新中", Toast.LENGTH_SHORT).show();
                refresheMoreData(++mRefreshPage);

            }
        });


        //上拉加载n
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == mAdapter.getItemCount()) {
                    Toast.makeText(UIUtils.getContext(), "上拉加载中", Toast.LENGTH_SHORT).show();
                    loadMoreData(++mLoadPage);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
            }
        });

        /*//点击事件
        mAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                // Toast.makeText(UIUtils.getContext(), "点击" + position + "###", Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(getActivity(), NewsDetailActivity.class);
                News mNews = mAdapter.getDatas().get(position);
                intent.putExtra("news",mNews);
                startActivity(intent);
            }
        });*/

    }

    @Override
    protected void loadData() {
        mCommonPager.isReadData = true;
        mHttpUtils = new HttpUtils<>();
        mParams = new HashMap<>();
        mParams.put("page", "0");
        mHttpUtils.getData(Constants.Http.HOTSPOT, mParams, NewsList.class, new HttpUtils.OnHttpResponseListener<NewsList>() {
            @Override
            public void onSuccess(NewsList bean) {
                mNews = bean.getList();
                mCommonPager.dealCommonSuccess(mNews);
            }

            @Override
            public void onFailure(Exception e) {
                mCommonPager.dealCommonFailure();
            }
        });

    }

    //下拉记载更多，网络请求与UI更改
    private void loadMoreData(int page) {
        mParams.clear();
        mParams.put("page", String.valueOf(page));
        mHttpUtils.getData(Constants.Http.HOTSPOT, mParams, NewsList.class,
                new HttpUtils.OnHttpResponseListener<NewsList>() {

                    @Override
                    public void onSuccess(NewsList bean) {
                        try {
                            mLoadNewses = bean.getList();

                            BaseApplication.mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mAdapter.addLoadItem(mLoadNewses);
                                    Toast.makeText(UIUtils.getContext(), "下拉加载完成", Toast.LENGTH_SHORT).show();
                                }
                            }, 3000);

                        } catch (Exception e) {
                            BaseApplication.mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(UIUtils.getContext(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                                    --mLoadPage;
                                }
                            }, 3000);
                        }


                    }

                    @Override
                    public void onFailure(Exception e) {

                    }

                });

    }

    //上拉刷新和UI更改
    private void refresheMoreData(int page) {
        mParams.clear();
        mParams.put("page", String.valueOf(page));

        mHttpUtils.getData(Constants.Http.HOTSPOT, mParams, NewsList.class,
                new HttpUtils.OnHttpResponseListener<NewsList>() {

                    @Override
                    public void onSuccess(NewsList bean) {
                        try {
                            mRefreshNewses = bean.getList();

                            BaseApplication.mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mAdapter.addRefreshItem(mRefreshNewses);
                                    mSwipeRefreshLayout.setRefreshing(false);
                                    Toast.makeText(UIUtils.getContext(), "下拉刷新完成", Toast.LENGTH_SHORT).show();
                                }
                            }, 3000);

                        } catch (Exception e) {
                            BaseApplication.mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mSwipeRefreshLayout.setRefreshing(false);
                                    Toast.makeText(UIUtils.getContext(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                                    --mRefreshPage;
                                }
                            }, 3000);
                        }


                    }

                    @Override
                    public void onFailure(Exception e) {

                    }

                });

    }
}
